package com.nlscan.qdkit.ui.publico.component.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StyleRes;

import com.nlscan.qdkit.ui.publico.R;
import com.nlscan.qdkit.ui.publico.config.InputCheckHelper;
import com.nlscan.qdkit.ui.publico.util.RtlUtils;
import com.quvii.qvlib.util.QvTextUtil;

/**
 * 自定义dialog
 * Created by yuanpeng.deng on 2017/11/17.
 * todo update
 */

public class MyDialog2 extends Dialog {
    private Button positiveButton;
    private Button negativeButton;
    private TextView titleView;
    private TextView messageView;
    private ProhibitCopyEditText editTextView;
    private ImageView editShowImageView;
    private FrameLayout editFreameLayout;
    private LinearLayout llRoot;
    private CheckBox checkBox;

    private String positiveStr;
    private String negativeStr;
    private String titleStr;
    private String message;
    private String editText;
    private String etMessage;
    private String cbText;

    private boolean isShowOrHideEdit = false;
    private boolean isEditNum = false;
    private boolean isEditPwd = false;

    private boolean isPwdShowIconSelect = false;
    private int etInputMaxLength = -1;
    private boolean isEditTrim = false; //是否要检测输入全为空格和去掉两端的空格

    private int etInputMaxBytes = -1;       // 可输入最大字节数
    private String etInputFilterRegex = ""; // 输入框需过滤的正则表达式（要过滤哪些特殊字符）

    private onNegativeClickListener onNegativeClickListener;//取消按钮被点击了的监听器
    private onPositiveClickListener onPositiveClickListener;//确定按钮被点击了的监听器
    private onMessageClickListener onMessageClickListener;  // message点击事件
    private OnCheckChangeListener onCheckChangeListener;

    private Context context;
    private QvTextUtil.ClickBlock[] clickBlockList;
    private QvTextUtil.ClickBlock[] clickBlockList2;

    // dialog内间距
    private boolean isCustomPadding = false;
    private int paddingLeft, paddingTop, paddingRight, paddingBottom;

    private boolean isChecked = false;

    public MyDialog2(@NonNull Context context) {
        super(context, R.style.MyDialog);
        this.context = context;
    }

    public MyDialog2(@NonNull Context context, @StyleRes int theme) {
        super(context, theme);
    }

    protected MyDialog2(@NonNull Context context, boolean cancelable, @Nullable OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_dialog);
        Window mWindow = getWindow();
        if (mWindow != null) {
            mWindow.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        initView();
        initData();
        initEvent();
    }

    public void setNegativeClickListener(String str, onNegativeClickListener onNegativeClickListener) {
        if (str != null) {
            negativeStr = str;
        }
        this.onNegativeClickListener = onNegativeClickListener;
    }

    public void setNegativeClickListener(int res, onNegativeClickListener onNegativeClickListener) {
        this.negativeStr = context.getString(res);
        this.onNegativeClickListener = onNegativeClickListener;
    }

    public void setPositiveClickListener(String str, onPositiveClickListener onYesOnclickListener) {
        if (str != null) {
            positiveStr = str;
        }
        this.onPositiveClickListener = onYesOnclickListener;
    }

    public void setPositiveClickListener(int res, onPositiveClickListener onYesOnclickListener) {
        this.positiveStr = context.getString(res);
        this.onPositiveClickListener = onYesOnclickListener;
    }

    public void setMessageClickListener(int strId, onMessageClickListener onMessageClickListener) {
        this.message = context.getString(strId);
        this.onMessageClickListener = onMessageClickListener;
    }

    public void setMessageClickListener(String str, onMessageClickListener onMessageClickListener) {
        if (str != null) {
            this.message = str;
        }
        this.onMessageClickListener = onMessageClickListener;
    }

    public void setCheckBoxText(int strId) {
        this.cbText = context.getString(strId);
    }

    public void setCheckChangeListener(int strId, OnCheckChangeListener listener) {
        this.cbText = context.getString(strId);
        this.onCheckChangeListener = listener;
    }

    public void setCheckChangeListener(String str, OnCheckChangeListener listener) {
        if (str != null) {
            this.cbText = str;
        }
        this.onCheckChangeListener = listener;
    }

    public void setTitle(String title) {
        this.titleStr = title;
    }

    public void setTitle(int res) {
        this.titleStr = context.getString(res);
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setMessage(int res) {
        this.message = context.getString(res);
    }

    public void setEditHintText(String editText) {
        this.editText = editText;
    }

    public void setEditHintText(int res) {
        this.editText = context.getString(res);
    }

    public void setEtInputMaxLength(int etInputMaxLength) {
        this.etInputMaxLength = etInputMaxLength;
    }

    public void setEtInputMaxBytes(int maxBytes) {
        this.etInputMaxBytes = maxBytes;
    }

    public void setEtInputFilterRegex(String regex) {
        this.etInputFilterRegex = regex;
    }

    public String getEditText() {
        return isEditTrim ? editTextView.getText().toString().trim() : editTextView.getText().toString();
    }

    public void setShowOrHideEdit(boolean value) {
        this.isShowOrHideEdit = value;
    }

    public void setEditNum(boolean editNum) {
        isEditNum = editNum;
    }

    public void setEditPwd(boolean editPwd) {
        this.isEditPwd = editPwd;
    }

    public boolean isChecked() {
        return isChecked;
    }

    public void setMessageClickBlock(QvTextUtil.ClickBlock... clickBlock) {
        clickBlockList = clickBlock;
    }

    public void setMessageClickBlock2(QvTextUtil.ClickBlock... clickBlock) {
        clickBlockList2 = clickBlock;
    }

    /**
     * 初始化界面的确定和取消监听器
     */
    private void initEvent() {
        //设置确定按钮被点击后，向外界提供监听
        positiveButton.setOnClickListener(v -> {
            if (onPositiveClickListener != null) {
                onPositiveClickListener.onClick();
            }
        });
        //设置取消按钮被点击后，向外界提供监听
        negativeButton.setOnClickListener(v -> {
            if (onNegativeClickListener != null) {
                onNegativeClickListener.onClick();
            }
        });
        messageView.setOnClickListener(v -> {
            if (onMessageClickListener != null) {
                onMessageClickListener.onClick();
            }
        });

        checkBox.setChecked(false);
        checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            this.isChecked = isChecked;
            if (onCheckChangeListener != null) {
                onCheckChangeListener.onCheckChange(isChecked);
            }
        });
    }

    /**
     * 初始化界面控件的显示数据
     */
    private void initData() {
        //如果用户自定了title和message
        if (titleStr != null) {
            titleView.setText(titleStr);
        } else {
            titleView.setVisibility(View.GONE);
        }

        if (message != null) {
            messageView.setText(message);
            if (clickBlockList != null) {
                QvTextUtil.setClickText(
                        messageView,
                        message,
                        clickBlockList
                );
            } else if (clickBlockList2 != null) {
                QvTextUtil.setClickText2(
                        messageView,
                        message,
                        clickBlockList2
                );
            }
        } else {
            messageView.setVisibility(View.GONE);
        }

        //如果设置按钮的文字
        if (positiveStr != null) {
            positiveButton.setText(positiveStr);
        } else {
            positiveButton.setVisibility(View.GONE);
        }

        if (negativeStr != null) {
            negativeButton.setText(negativeStr);
        } else {
            negativeButton.setVisibility(View.GONE);
        }

        if (editText != null) {
            editTextView.setHint(editText);
            RtlUtils.dealWithEdit(editTextView);
            Window window = getWindow();
            if (window != null) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
            }

            if (etInputMaxBytes > 0) {
                InputCheckHelper.setEditTextInputFilter(editTextView, etInputFilterRegex, etInputMaxBytes);
            } else if (etInputMaxLength > 0) {
                editTextView.setFilters(new InputFilter[]{new InputFilter.LengthFilter(etInputMaxLength)});
                if (window != null) {
                    window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
                }
            }
        } else {
            editTextView.setVisibility(View.GONE);
            editFreameLayout.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(etMessage)) {
            editTextView.setText(etMessage);
            editTextView.setSelection(editTextView.getText().toString().length());
        }

        if (isEditNum) {
            editTextView.setInputType(InputType.TYPE_CLASS_NUMBER);
        }

        if (isEditPwd) {
            editTextView.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }

        if (isShowOrHideEdit) {
            editShowImageView.setOnClickListener(v -> showOrHidePwd());
            editTextView.setTransformationMethod(PasswordTransformationMethod.getInstance());
        } else {
            editShowImageView.setVisibility(View.GONE);
        }

        if (TextUtils.isEmpty(cbText)) {
            checkBox.setVisibility(View.GONE);
        } else {
            checkBox.setVisibility(View.VISIBLE);
            checkBox.setText(cbText);
        }

    }

    private void initView() {



        //debug0330
        Log.d("TAG41","initView start");
        positiveButton = findViewById(R.id.yes);
        negativeButton = findViewById(R.id.no);
        titleView = findViewById(R.id.title);
        messageView = findViewById(R.id.message);
        editTextView = findViewById(R.id.my_dialog_edit);
        editShowImageView = findViewById(R.id.my_dialog_show_edit);
        editFreameLayout = findViewById(R.id.my_dialog_edit_frame);
        checkBox = findViewById(R.id.my_dialog_checkbox);
        if (isCustomPadding) {
            llRoot = findViewById(R.id.root);
            llRoot.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
        }
    }

    public void setEtInputLimit(int maxBytes, String regex) {
        this.etInputMaxBytes = maxBytes;
        this.etInputFilterRegex = regex;
    }

    public void setEditTrim(boolean editTrim) {
        isEditTrim = editTrim;
    }

    private void showOrHidePwd() {
        if (isPwdShowIconSelect) {
            isPwdShowIconSelect = false;
            editTextView.setTransformationMethod(PasswordTransformationMethod.getInstance());
            editShowImageView.setImageResource(R.drawable.pubilco_btn_show_password_big);
        } else {
            isPwdShowIconSelect = true;
            editTextView.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            editShowImageView.setImageResource(R.drawable.pubilco_btn_show_password_big_selected);
        }
        editTextView.setSelection(editTextView.getText().length());
    }

    public void setEtMessage(String name) {
        etMessage = name;
    }

    public void setDialogPadding(int left, int top, int right, int bottom) {
        this.isCustomPadding = true;
        paddingLeft = left;
        paddingTop = top;
        paddingRight = right;
        paddingBottom = bottom;
    }

    public static class Builder {
        public static MyDialog2 GenerateCommonDialog(Context context, int messageRes, onPositiveClickListener onPositiveClickListener) {
            return GenerateCommonDialog(context, context.getString(messageRes), onPositiveClickListener);
        }

        public static MyDialog2 GenerateCommonDialog(Context context, String message, onPositiveClickListener onPositiveClickListener) {
            MyDialog2 myDialog2 = new MyDialog2(context);
            myDialog2.setMessage(message);
            myDialog2.setPositiveClickListener(R.string.publico_ok, () -> {
                myDialog2.dismiss();
                onPositiveClickListener.onClick();
            });
            myDialog2.setNegativeClickListener(R.string.publico_cancel, myDialog2::dismiss);
            return myDialog2;
        }

        public static void ShowCommonDialog(Context context, int messageRes, onPositiveClickListener onPositiveClickListener) {
            GenerateCommonDialog(context, messageRes, onPositiveClickListener).show();
        }

        public static MyDialog2 GenerateInfoDialog(Context context, int messageRes) {
            MyDialog2 myDialog2 = new MyDialog2(context);
            myDialog2.setMessage(messageRes);
            myDialog2.setPositiveClickListener(R.string.publico_ok, myDialog2::dismiss);
            return myDialog2;
        }

        public static MyDialog2 GenerateCommonDialog(Context context, int messageRes,
                                                     onPositiveClickListener onPositiveClickListener,
                                                     onNegativeClickListener onNegativeClickListener) {
            MyDialog2 myDialog2 = new MyDialog2(context);
            myDialog2.setMessage(messageRes);
            myDialog2.setPositiveClickListener(R.string.publico_ok, () -> {
                myDialog2.dismiss();
                onPositiveClickListener.onClick();
            });
            myDialog2.setNegativeClickListener(R.string.publico_cancel, () -> {
                myDialog2.dismiss();
                onNegativeClickListener.onClick();
            });
            myDialog2.setNegativeClickListener(R.string.publico_cancel, myDialog2::dismiss);
            return myDialog2;
        }
    }

    /**
     * 设置确定按钮和取消被点击的接口
     */
    public interface onPositiveClickListener {
        void onClick();
    }

    public interface onNegativeClickListener {
        void onClick();
    }

    public interface onMessageClickListener {
        void onClick();
    }

    public interface OnCheckChangeListener {
        void onCheckChange(boolean isChecked);
    }

}